package com.arlen.general.util;

import com.alibaba.fastjson.JSON;
import com.arlen.general.exceptionHandle.WxCustomException;
import com.arlen.general.pojo.QiingYunke;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;


/**
 * @Author Arlen
 * @Description 用于发送聊天机器人请求
 * @Date 7:56 下午 2021/4/18
 **/
public class HttpRequest  {
    //单列封装性能会好一些，在不考虑线程因素下
    private static HttpRequest httpRequest;

    private HttpRequest() {
    }

    public static HttpRequest getHttpRequest() {
        if (httpRequest == null) {
            return new HttpRequest();
        }
        return httpRequest;
    }

    private  static final Properties properties;
    static {
        properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = HttpRequest.class.getClassLoader().getResourceAsStream("needed.properties");
        // 使用properties对象加载输入流
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class);

    public String sendGet(String url, QiingYunke qy) throws WxCustomException {
        if (url == null) {
            url = properties.getProperty("qingyunke.url");
        }
        StringBuilder builder = new StringBuilder(url);
        url = builder.append("?key=" + qy.getKey())
                .append("&appid=" + qy.getAppid()).append("&msg=" + qy.getMes()).toString();
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection urlConnection = (HttpURLConnection) httpUrl.openConnection();
            if (urlConnection.getResponseCode()!=200){
                throw new WxCustomException("Request Error !");
            }
            InputStream urlConnectionInputStream = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnectionInputStream));
            String responseMes = reader.readLine();
            if (!StringUtils.isBlank(responseMes)){
                Map<String,Object> map = JSON.parseObject(responseMes, Map.class);
                if (!map.get("result").equals(0)){
                    return  null;
                }
                return (String) map.get("content");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


}
